package com.iwhalecloud.uncc.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;


import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zq
 * @date 2021/10/14 16:29
 * @description 线程池配置
 */
@Configuration
@EnableAsync
@Slf4j
public class ThreadPoolConfiguration {

    /**
     * 核心线程数（默认线程数）
     */
    @Value("${threadPool.taskExecutor.corePoolSize}")
    private int corePoolSize = 24;
    /**
     * 最大线程数
     */
    @Value("${threadPool.taskExecutor.maxPoolSize}")
    private int maxPoolSize = 100;
    /**
     * 任务线程池名前缀
     */
    @Value("${threadPool.taskExecutor.threadNamePrefix}")
    private String threadNamePrefix = "Task-Thread-";
    /**
     * 线程空闲时间（单位：默认为秒）
     */
    @Value("${threadPool.taskExecutor.keepAliveTime}")
    private int keepAliveTime = 10;
    /**
     * 缓冲队列数
     */
    @Value("${threadPool.taskExecutor.queueCapacity}")
    private int queueCapacity = 200;




    /**
     * 处理任务线程池
     */
    @Bean("taskExecutor")
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setKeepAliveSeconds(keepAliveTime);
        taskExecutor.setThreadNamePrefix(threadNamePrefix);
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        log.info("taskExecutor 初始化成功！");
        Executor executor = TtlExecutors.getTtlExecutor(taskExecutor);
        log.info("taskExecutor TTL包装成功！");
        return executor;
    }

    /**
     * 调度线程池名前缀
     */
    @Value("${threadPool.taskScheduler.threadNamePrefix}")
    private String prefix = "Scheduler-Thread-";
    /**
     * 核心线程数（默认线程数）
     */
    @Value("${threadPool.taskScheduler.corePoolSize}")
    private int poolSize = 2;

    /**
     * 定时任务线程池
     * @return taskScheduler
     */
    @Bean("taskScheduler")
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setThreadNamePrefix(prefix);
        taskScheduler.setPoolSize(poolSize);
        taskScheduler.initialize();
        log.info("taskScheduler 初始化成功！");
        return taskScheduler;
    }
}
